using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UserLoging.Database;
using UserLoging.Services;

namespace UserLoging
{
    public class Startup
    {
        private IConfiguration _configuration { get; }
       readonly string  myCors = "cors";
        public Startup(IConfiguration configuration) 
        {
            _configuration = configuration;
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(option =>
            {
                option.AddPolicy(myCors, bulider =>
                {
                    bulider.WithOrigins(string.Format(@"http://localhost:8080")).AllowAnyHeader().AllowCredentials().WithMethods("GET","POST","OPTIONS","PUT","DELETE","PATCH");
                });
            });
            services.AddControllers();
            services.AddDbContext<UserDbContext>(options =>
            {
                options.UseSqlServer(_configuration["DbContext:ConnectionString"]);
            });
            services.AddTransient<IUserRepository, UserRepository>();
            var keyByBase64 = "lixiannulixiannu";
            var keyByArray = Encoding.UTF8.GetBytes(keyByBase64);
            var signngKey = new SymmetricSecurityKey(keyByArray);
            var tokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signngKey,
                ValidateIssuer = true,
                ValidIssuer = "https://localhost:44389/",
                ValidateAudience = true,
                ValidAudience = "https://localhost:8080/",
                ValidateLifetime = true,
            };
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o => o.TokenValidationParameters = tokenValidationParameters);
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseCors();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers().RequireCors(myCors);
                
            });
        }
    }
}
